<template>
  <div class="conversation-history">
    <!-- 搜索和筛选 -->
    <div class="history-filters">
      <el-row :gutter="16">
        <el-col :span="8">
          <el-input
            v-model="filters.sessionId"
            placeholder="会话ID"
            clearable
          />
        </el-col>
        <el-col :span="6">
          <el-date-picker
            v-model="filters.startTime"
            type="date"
            placeholder="开始日期"
            style="width: 100%"
          />
        </el-col>
        <el-col :span="6">
          <el-date-picker
            v-model="filters.endTime"
            type="date"
            placeholder="结束日期"
            style="width: 100%"
          />
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="loadHistory" :loading="loading">
            查询
          </el-button>
        </el-col>
      </el-row>
    </div>

    <!-- 历史记录列表 -->
    <div class="history-list">
      <el-table
        :data="historyList"
        v-loading="loading"
        @row-click="selectConversation"
        style="width: 100%"
        height="400"
      >
        <el-table-column prop="sessionId" label="会话ID" width="200" />
        <el-table-column prop="startTime" label="开始时间" width="180">
          <template #default="scope">
            {{ formatDateTime(scope.row.startTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="endTime" label="结束时间" width="180">
          <template #default="scope">
            {{ scope.row.endTime ? formatDateTime(scope.row.endTime) : '进行中' }}
          </template>
        </el-table-column>
        <el-table-column prop="messageCount" label="消息数量" width="100" />
        <el-table-column prop="satisfaction" label="满意度" width="120">
          <template #default="scope">
            <el-rate
              v-if="scope.row.satisfaction"
              :model-value="scope.row.satisfaction"
              disabled
              size="small"
            />
            <span v-else class="text-gray">未评价</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120">
          <template #default="scope">
            <el-button
              type="text"
              size="small"
              @click.stop="viewConversation(scope.row)"
            >
              查看详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页 -->
    <div class="history-pagination">
      <el-pagination
        v-model:current-page="pagination.pageIndex"
        v-model:page-size="pagination.pageSize"
        :total="pagination.total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="loadHistory"
        @current-change="loadHistory"
      />
    </div>

    <!-- 对话详情对话框 -->
    <el-dialog
      v-model="showDetail"
      :title="`对话详情 - ${selectedConversation?.sessionId}`"
      width="70%"
      top="5vh"
    >
      <div class="conversation-detail">
        <div class="detail-messages" ref="detailContainer">
          <div
            v-for="(message, index) in conversationDetail"
            :key="index"
            :class="['detail-message', message.type]"
          >
            <div class="message-meta">
              <span class="sender">{{ message.type === 'user' ? '用户' : 'AI助手' }}</span>
              <span class="time">{{ formatDateTime(message.timestamp) }}</span>
            </div>
            <div class="message-content" v-html="message.content"></div>
          </div>
        </div>
      </div>
      <template #footer>
        <el-button @click="showDetail = false">关闭</el-button>
        <el-button type="primary" @click="loadConversation">加载此对话</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { AICustomerService } from '@/services/aiCustomerService'

// 事件定义
const emit = defineEmits<{
  selectConversation: [conversation: any]
}>()

// 响应式数据
const loading = ref(false)
const showDetail = ref(false)
const historyList = ref<any[]>([])
const conversationDetail = ref<any[]>([])
const selectedConversation = ref<any>(null)

// 筛选条件
const filters = ref({
  sessionId: '',
  startTime: '',
  endTime: ''
})

// 分页
const pagination = ref({
  pageIndex: 1,
  pageSize: 20,
  total: 0
})

// 初始化
onMounted(() => {
  loadHistory()
})

// 加载历史记录
const loadHistory = async () => {
  loading.value = true
  try {
    const params = {
      sessionId: filters.value.sessionId || undefined,
      startTime: filters.value.startTime || undefined,
      endTime: filters.value.endTime || undefined,
      pageIndex: pagination.value.pageIndex,
      pageSize: pagination.value.pageSize
    }
    
    const response = await AICustomerService.getConversationHistory(params)
    
    if (response.code === 200) {
      historyList.value = response.data?.data || []
      pagination.value.total = response.data?.total || 0
    } else {
      ElMessage.error(response.msg || '获取历史记录失败')
    }
  } catch (error) {
    ElMessage.error('获取历史记录失败')
  } finally {
    loading.value = false
  }
}

// 选择对话
const selectConversation = (conversation: any) => {
  selectedConversation.value = conversation
  emit('selectConversation', conversation)
}

// 查看对话详情
const viewConversation = async (conversation: any) => {
  selectedConversation.value = conversation
  showDetail.value = true
  
  // 这里应该调用获取对话详细消息的API
  // 由于API文档中没有提供，这里模拟数据
  conversationDetail.value = [
    {
      type: 'user',
      content: '你好，我需要帮助',
      timestamp: new Date(conversation.startTime)
    },
    {
      type: 'ai',
      content: '您好！我是智能客服助手，很高兴为您服务。请问有什么可以帮助您的吗？',
      timestamp: new Date(conversation.startTime)
    }
    // 实际应该从API获取完整的对话记录
  ]
}

// 加载对话到当前聊天
const loadConversation = () => {
  if (selectedConversation.value) {
    emit('selectConversation', selectedConversation.value)
    showDetail.value = false
  }
}

// 格式化日期时间
const formatDateTime = (dateStr: string) => {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  return date.toLocaleString('zh-CN')
}
</script>

<style scoped>
.conversation-history {
  padding: 0;
}

.history-filters {
  margin-bottom: 20px;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 6px;
}

.history-list {
  margin-bottom: 20px;
}

.history-pagination {
  display: flex;
  justify-content: center;
  padding: 16px 0;
}

.conversation-detail {
  max-height: 60vh;
  overflow-y: auto;
}

.detail-messages {
  padding: 10px;
}

.detail-message {
  margin-bottom: 16px;
  padding: 12px;
  border-radius: 8px;
  background: #f8f9fa;
}

.detail-message.user {
  background: #e3f2fd;
  margin-left: 20%;
}

.detail-message.ai {
  background: #f1f8e9;
  margin-right: 20%;
}

.message-meta {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
  font-size: 12px;
  color: #666;
}

.sender {
  font-weight: 600;
}

.message-content {
  line-height: 1.5;
  word-wrap: break-word;
}

.text-gray {
  color: #999;
}

:deep(.el-table__row) {
  cursor: pointer;
}

:deep(.el-table__row:hover) {
  background-color: #f5f7fa;
}
</style>
